using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using mojoPortal.Web;
using ud_Article.Business;
using Resources;
using ud_Utilities;

namespace ud_Article.UI
{
    public partial class ArticlePropertyEdit : mojoBasePage
    {
        readonly DBAticleProperties repository = new DBAticleProperties();
        private int pageId = -1;
        private int moduleId = -1;
        private Guid itemGuid = Guid.Empty;
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;
        protected string ViewContentImage = "View.png";
        protected string Path;

        private ud_ArticleProperty item;
        private ArticleConfiguration config = new ArticleConfiguration();

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("EditItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                WebUtils.SetupRedirect(this, SiteRoot + "/Article/EditProperty.aspx?pageid="
                    + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&pguid=" + itemGuid);
            }
            else if (e.CommandName.Equals("DeleteItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                repository.Delete(itemGuid);
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
            }
            else if (e.CommandName.Equals("Down"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                if (item == null) item = repository.GetOne(itemGuid);
                if (item == null) return;
                if (item.OrderNumber <= 0) return;
                int orderNumber = item.OrderNumber - 1;
                repository.Update(item.Guid, item.Property, item.Unit, orderNumber);
                BindData();
            }
            else if (e.CommandName.Equals("Up"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                if (item == null) item = repository.GetOne(itemGuid);
                if (item == null) return;
                int orderNumber = item.OrderNumber + 1;
                repository.Update(item.Guid, item.Property, item.Unit, orderNumber);
                BindData();
            }
        }

        void gvItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvItems.PageIndex = e.NewPageIndex;
            BindData();
        }

        void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow) return;
            ImageButton ibtnDelete = e.Row.FindControl("ibtnDelete") as ImageButton;
            Utilities.AddConfirmButton(ibtnDelete, ArticleResources.DeleteConfirmation);
        }

        override protected void OnInit(EventArgs e)
        {
            LoadPanels();
            Load += Page_Load;
            btnSave.Click += btnSave_Click;
            gvItems.RowCommand += gvItems_RowCommand;
            gvItems.RowDataBound += gvItems_RowDataBound;
            gvItems.PageIndexChanging += gvItems_PageIndexChanging;
            base.OnInit(e);
        }

        #endregion

        private void BindData()
        {
            List<ud_ArticleProperty> items = repository.GetAll(moduleId);
            gvItems.DataSource = items;
            gvItems.DataBind();
            gvItems.AllowPaging = items.Count > 10;
        }

        private void LoadPanels()
        {
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            if (!Request.IsAuthenticated)
            {
                SiteUtils.RedirectToLoginPage(this);
                return;
            }
            SecurityHelper.DisableBrowserCache();

            LoadSettings();
            if (!WebUser.IsInRoles(config.RoleProperty))
            {
                SiteUtils.RedirectToEditAccessDeniedPage();
            }
            
            PopulateLabels();

            if (!Page.IsPostBack)
            {
                PopulateControls();
            }
        }

        private void PopulateLabels()
        {
            btnBack.Text = ArticleResources.ButtonBack;
            btnSave.Text = ArticleResources.ButtonSave;
            lblTitle.Text = ArticleResources.PropertyManage;
            gvItems.Columns[0].HeaderText = ArticleResources.NewPropertyLabel;
            gvItems.Columns[1].HeaderText = ArticleResources.NewUnitLabel;
            gvItems.Columns[2].HeaderText = ArticleResources.OrderNumber;
            Title = SiteUtils.FormatPageTitle(siteSettings, ArticleResources.PropertyManage);
            Path = ImageSiteRoot + "/Data/SiteImages/";
            if (Master == null) return;
            Control c = Master.FindControl("Breadcrumbs");
            if (c == null) return;
            BreadcrumbsControl crumbs = (BreadcrumbsControl)c;
            crumbs.ForceShowBreadcrumbs = true;
        }

        private void PopulateControls()
        {
            BindData();
            BindEdit();
        }

        private void BindEdit()
        {
            if (item == null) return;
            txtProperty.Text = item.Property;
            txtOrderNumber.Text = item.OrderNumber.ToString();
            txtUnit.Text = item.Unit;
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void Save()
        {
            if (itemGuid == Guid.Empty)
            {
                repository.Create(moduleId, txtProperty.Text, txtUnit.Text, Convert.ToInt32(txtOrderNumber.Text));
            }
            else
            {
                repository.Update(itemGuid, txtProperty.Text, txtUnit.Text, Convert.ToInt32(txtOrderNumber.Text));
            }
            WebUtils.SetupRedirect(this, SiteRoot + "/Article/EditProperty.aspx?pageid=" + pageId + "&mid=" + moduleId);
        }

        private void LoadSettings()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", -1);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            itemGuid = WebUtils.ParseGuidFromQueryString("pguid", itemGuid);
            item = repository.GetOne(itemGuid);

            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new ArticleConfiguration(settings);
        }
    }
}
